const announcementsProxy = require('../proxy/announcements')
const announcementTagsProxy = require('../proxy/announcement-tags')
const teamsProxy = require('../proxy/teams')
const fs = require('fs')
const path = require('path')

exports.getAllTagsInTeam = async function(req, res, next) {
  const { teamId } = req.params
  if (teamId !== req.user.teamId) {
    return res.status(403).end()
  }
  try {
    // get tags from team
    const { onlyTags } = req.query
    const tags = (await teamsProxy.getAllAnnTag(teamId, onlyTags)).announcement_tags
    res.json({ tags })
  } catch (err) {
    next(err)
  }
}

exports.createTag = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'announcement')) {
    return res.status(403).end()
  }
  try {
    const { name } = req.body
    if (!name) throw new Error('name should not be null')
    const tag = await announcementTagsProxy.create(name)
    // push in team
    await teamsProxy.addAnnTag(req.user.teamId, tag.id)
    res.json({ tag })
  } catch (err) {
    next(err)
  }
}

exports.removeTagFromTeam = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'announcement')) {
    return res.status(403).end()
  }
  try {
    const { tagId } = req.params
    // check it's in team and empty
    const allow = await announcementTagsProxy.isEmpty(tagId)
    if (allow) {
      res.status(200).end()
      // remove from tags model
      await announcementTagsProxy.remove(tagId)
      // remove from the team
      await teamsProxy.removeAnnTag(req.user.teamId, tagId)
    } else {
      res.status(204).end()
    }
  } catch (err) {
    next(err)
  }
}

exports.updateTagWithName = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'announcement')) {
    return res.status(403).end()
  }
  try {
    const { name } = req.body
    // update it and get new item
    const tag = await announcementTagsProxy.updateName(req.params.tagId, name)
    res.json({ tag })
  } catch (err) {
    next(err)
  }
}

exports.getAllAnnInTeam = async function(req, res, next) {
  const { teamId } = req.params
  if (teamId !== req.user.teamId) {
    return res.status(403).end()
  }
  try {
    let { page, per_page } = req.query
    if (!page || page < 1) page = 1
    if (!per_page || per_page < 1) per_page = 50
    const items = await announcementsProxy.getAllAnnInTeam(teamId, (page - 1) * per_page, per_page * 1)
    const total = await announcementsProxy.countAnns(teamId)
    for (const item of items) {
      item._doc.icon = new Buffer(item._doc.icon, 'binary').toString('base64')
    }
    res.json({ items, total })
  } catch (err) {
    next(err)
  }
}

exports.removeAnnouncement = async function(req, res, next) {
  if (!req.user.roles.some(v => v === 'admin' || v === 'announcement')) {
    return res.status(403).end()
  }
  try {
    // check the ann is in team
    // remove from ann
    const { announcementId } = req.params
    const deletedAnn = await announcementsProxy.removeAnnInTeam(announcementId, req.user.teamId)
    if (!deletedAnn) throw new Error()
    else {
      // remove from its anntags
      await announcementTagsProxy.removeAnnFromListInTag(announcementId, deletedAnn.announcement_tag)
      res.sendStatus(200)
    }
  } catch (err) {
    next(err)
  }
}

exports.createAnnInTeam = async function(req, res, next) {
  const { teamId } = req.params
  if (teamId !== req.user.teamId || !req.user.roles.some(v => v === 'admin' || v === 'announcement')) {
    return res.status(403).end()
  }
  try {
    const { announcement_tag, title, summary, content } = req.body
    let { icon } = req.body
    // icon to buffer
    if (icon) {
      const re = /data:image\/(ico|png|jpeg|jpg|gif);base64,(\S+)/
      icon = new Buffer(icon.replace(re, '$2'), 'base64')
    } else {
      icon = fs.readFileSync(path.join(__dirname, '../static/favicon.ico'))
    }
    // save to ann table
    const ann = await announcementsProxy.createAnn({ icon, announcement_tag, title, summary, content, author: req.user.userId, team: teamId })
    await announcementTagsProxy.addAnnToTagList(ann.id, announcement_tag)
    // add to annTag table
    res.json({ id: ann.id })
  } catch (err) {
    next(err)
  }
}

exports.getAnnouncement = async function(req, res, next) {
  try {
    // get with teamId limit
    const announcement = await announcementsProxy.getAnnInTeam(req.params.announcementId, req.user.teamId)
    // return
    announcement.icon = new Buffer(announcement.icon, 'binary').toString('base64')
    res.json({ ...announcement.toObject() })
  } catch (err) {
    next(err)
  }
}
